package czh.cocoa.ui;

import czh.cocoa.foundation.NSArray;
import czh.cocoa.graphics.CGRect;

public class UIWindow extends UIView {
	
	private UIViewController mRootViewController;

	public UIWindow() {
		
	}
	
	public UIWindow(CGRect frame) {
		super(frame);
	}
	
	public void setRootViewController(UIViewController root) {
		mRootViewController = root;
		clearAllSubviews();
		if (root != null) {
			UIView view = root.view();
			view.setFrame(bounds());
			view.setAutoresizingMask(UIViewAutoresizingFlexibleSize);
			addSubview(view);
		}
	}
	
	public UIViewController rootViewController() {
		return mRootViewController;
	}
	
	public void makeKeyAndVisible() {
		UIApplication.sharedApplication().setKeyWindow(this);
	}
	
	public UIResponder nextResponder() {
		return UIApplication.sharedApplication();
	}
	
	void resignKeyWindow() {
	
	}
	
	public void insertSubviewAtIndex(UIView view, int index) {
		notifyViewWillAppear(view);
		super.insertSubviewAtIndex(view, index);
		notifyViewDidAppear(view);
	}
	
	private void notifyViewWillAppear(UIView view) {
		UIViewController delegate = view.viewDelegate();
		if (delegate != null) {
			delegate.viewWillAppear();
		}
		NSArray subviews = view.subviews();
		for (int i = 0; i < subviews.count(); i++) {
			UIView subview = (UIView) subviews.objectAtIndex(i);
			notifyViewWillAppear(subview);
		}
	}
	
	private void notifyViewDidAppear(UIView view) {
		UIViewController delegate = view.viewDelegate();
		if (delegate != null) {
			delegate.viewDidAppear();
		}
		NSArray subviews = view.subviews();
		for (int i = 0; i < subviews.count(); i++) {
			UIView subview = (UIView) subviews.objectAtIndex(i);
			notifyViewDidAppear(subview);
		}
	}
	
//	private void notifyViewWillDisappear(UIView view) {
//		UIViewController delegate = view.viewDelegate();
//		if (delegate != null) {
//			delegate.viewWillDisappear();
//		}
//		NSArray subviews = view.subviews();
//		for (int i = 0; i < subviews.count(); i++) {
//			UIView subview = (UIView) subviews.objectAtIndex(i);
//			notifyViewWillDisappear(subview);
//		}
//	}
//	
//	private void notifyViewDidDisappear(UIView view) {
//		UIViewController delegate = view.viewDelegate();
//		if (delegate != null) {
//			delegate.viewDidDisappear();
//		}
//		NSArray subviews = view.subviews();
//		for (int i = 0; i < subviews.count(); i++) {
//			UIView subview = (UIView) subviews.objectAtIndex(i);
//			notifyViewDidDisappear(subview);
//		}
//	}
	
}
